// 安全获取ElMessage - 参考 batch-combine3 的实现
let ElMessage;

// 创建自定义消息提示函数
function createCustomMessage() {
    return {
        success: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.log('Success:', message);
            showCustomMessage(message, 'success');
        },
        error: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.error('Error:', message);
            showCustomMessage(message, 'error');
        },
        warning: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.warn('Warning:', message);
            showCustomMessage(message, 'warning');
        },
        info: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.info('Info:', message);
            const msgObj = showCustomMessage(message, 'info');
            return {
                close: function() {
                    if (msgObj && msgObj.element) {
                        document.body.removeChild(msgObj.element);
                    }
                }
            };
        }
    };
}

// 显示自定义消息提示
function showCustomMessage(message, type) {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.style.position = 'fixed';
    messageElement.style.top = '20px';
    messageElement.style.left = '50%';
    messageElement.style.transform = 'translateX(-50%)';
    messageElement.style.padding = '10px 20px';
    messageElement.style.borderRadius = '4px';
    messageElement.style.zIndex = '9999';
    messageElement.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    messageElement.style.transition = 'opacity 0.3s, transform 0.3s';
    messageElement.style.opacity = '0';
    messageElement.style.transform = 'translateX(-50%) translateY(-20px)';
    messageElement.textContent = message;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            messageElement.style.backgroundColor = '#f0f9eb';
            messageElement.style.color = '#67c23a';
            messageElement.style.border = '1px solid #e1f3d8';
            break;
        case 'error':
            messageElement.style.backgroundColor = '#fef0f0';
            messageElement.style.color = '#f56c6c';
            messageElement.style.border = '1px solid #fde2e2';
            break;
        case 'warning':
            messageElement.style.backgroundColor = '#fdf6ec';
            messageElement.style.color = '#e6a23c';
            messageElement.style.border = '1px solid #faecd8';
            break;
        case 'info':
        default:
            messageElement.style.backgroundColor = '#edf2fc';
            messageElement.style.color = '#909399';
            messageElement.style.border = '1px solid #ebeef5';
            break;
    }
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 触发重绘以应用过渡效果
    setTimeout(() => {
        messageElement.style.opacity = '1';
        messageElement.style.transform = 'translateX(-50%) translateY(0)';
    }, 10);
    
    // 自动关闭（除非是info类型且duration为0）
    const duration = type === 'info' ? 0 : 3000;
    if (duration > 0) {
        setTimeout(() => {
            messageElement.style.opacity = '0';
            messageElement.style.transform = 'translateX(-50%) translateY(-20px)';
            
            setTimeout(() => {
                if (document.body.contains(messageElement)) {
                    document.body.removeChild(messageElement);
                }
            }, 300);
        }, duration);
    }
    
    return { element: messageElement };
}

// 尝试获取ElementPlus，如果不可用则使用自定义消息提示
try {
    if (window.ElementPlus && window.ElementPlus.ElMessage) {
        console.log('成功加载ElementPlus.ElMessage');
        ElMessage = window.ElementPlus.ElMessage;
    } else {
        console.warn('ElementPlus或ElMessage未找到，将使用自定义消息提示');
        ElMessage = createCustomMessage();
    }
} catch (error) {
    console.error('加载ElementPlus时出错:', error);
    ElMessage = createCustomMessage();
}

// 进度条管理
class ProgressManager {
    constructor() {
        this.progressBar = document.getElementById('progress-bar');
        this.progressText = document.getElementById('progress-text');
        this.progressContainer = document.getElementById('progress-container');
    }

    show() {
        if (this.progressContainer) {
            this.progressContainer.style.display = 'block';
        }
    }

    hide() {
        if (this.progressContainer) {
            this.progressContainer.style.display = 'none';
        }
    }

    update(current, total, text = '') {
        const percentage = total > 0 ? (current / total) * 100 : 0;
        if (this.progressBar) {
            this.progressBar.style.width = `${percentage}%`;
        }
        if (this.progressText) {
            this.progressText.textContent = text || `${current}/${total} (${percentage.toFixed(1)}%)`;
        }
    }
}

// 日志管理
class LogManager {
    constructor() {
        this.logContainer = document.getElementById('log-container');
        this.logContent = document.getElementById('log-content');
        this.clearBtn = document.getElementById('clear-logs');
        this.setupEventListeners();
    }

    setupEventListeners() {
        if (this.clearBtn) {
            this.clearBtn.addEventListener('click', () => this.clear());
        }
    }

    addLog(message, type = 'info') {
        if (!this.logContent) return;

        const logEntry = document.createElement('div');
        logEntry.className = `log-item ${type}`;
        
        const timestamp = new Date().toLocaleTimeString();
        logEntry.innerHTML = `
            <span class="log-time">[${timestamp}]</span>
            <span class="log-message">${message}</span>
        `;

        this.logContent.appendChild(logEntry);
        this.logContent.scrollTop = this.logContent.scrollHeight;
    }

    clear() {
        if (this.logContent) {
            this.logContent.innerHTML = '';
        }
    }

    show() {
        if (this.logContainer) {
            this.logContainer.style.display = 'block';
        }
    }

    hide() {
        if (this.logContainer) {
            this.logContainer.style.display = 'none';
        }
    }
}

// 全局变量
let progressManager;
let logManager;
let isProcessing = false;
let uploadedData = [];
let processingMessage = null;

// DOM 元素
let progressContainer, progressBar, progressText;
let startButton, stopButton, fileInput;
let envSwitch, headlessSwitch;
let resultContainer, logContainer, dataPreview;

// 初始化
function init() {
    // 获取 DOM 元素
    progressContainer = document.getElementById('progress-container');
    progressBar = document.getElementById('progress-bar');
    progressText = document.getElementById('progress-text');
    startButton = document.getElementById('start-button');
    stopButton = document.getElementById('close-preview');
    fileInput = document.getElementById('file-input');
    envSwitch = document.getElementById('switch');
    headlessSwitch = document.getElementById('headless-switch');
    resultContainer = document.getElementById('result-container');
    logContainer = document.getElementById('log-container');
    dataPreview = document.getElementById('data-preview');
    
    console.log('DOM元素初始化:', {
        resultContainer: !!resultContainer,
        logContainer: !!logContainer,
        dataPreview: !!dataPreview
    });
    
    progressManager = new ProgressManager();
    logManager = new LogManager();
    
    setupEventListeners();
    setupToggleSwitches();
    initializeUI();
    checkPluginAPI();
}

document.addEventListener('DOMContentLoaded', function() {
    init();
});

// 事件监听器设置
function setupEventListeners() {
    // 文件上传
    const fileInput = document.getElementById('file-input');
    if (fileInput) {
        fileInput.addEventListener('change', handleFileUpload);
        
        // 显示文件名
        fileInput.addEventListener('change', function(event) {
            const fileName = document.getElementById('file-name');
            if (fileName && event.target.files[0]) {
                fileName.textContent = event.target.files[0].name;
                fileName.style.display = 'block';
            }
        });
    }

    // 下载模板
    const downloadBtn = document.getElementById('download-template');
    if (downloadBtn) {
        downloadBtn.addEventListener('click', downloadTemplate);
    }

    // 开始处理
    const startBtn = document.getElementById('start-button');
    if (startBtn) {
        startBtn.addEventListener('click', startProcessing);
    }

    // 停止处理
    const stopBtn = document.getElementById('close-preview');
    if (stopBtn) {
        stopBtn.addEventListener('click', stopProcessing);
    }
}

// 切换开关设置
function setupToggleSwitches() {
    // 环境切换 - 新的 HTML 结构使用 checkbox-wrapper-35 样式，不需要额外的标签更新
    const envSwitch = document.getElementById('switch');
    if (envSwitch) {
        envSwitch.addEventListener('change', function() {
            console.log('环境切换:', this.checked ? 'PRD' : 'UAT');
        });
    }

    // 无头模式切换 - 新的 HTML 结构使用 checkbox-wrapper-35 样式，不需要额外的标签更新
    const headlessSwitch = document.getElementById('headless-switch');
    if (headlessSwitch) {
        headlessSwitch.addEventListener('change', function() {
            console.log('模式切换:', this.checked ? '显示步骤（有头模式）' : '隐藏步骤（无头模式）');
        });
    }
}

// 更新进度条
function updateProgress(current, total = 100, show = true, message = '') {
    if (!show) {
        if (progressContainer) {
            progressContainer.style.display = 'none';
        }
        return;
    }
    
    if (progressContainer) {
        progressContainer.style.display = 'block';
    }
    
    const percentage = total > 0 ? (current / total) * 100 : 0;
    if (progressBar) {
        progressBar.style.width = `${percentage}%`;
    }
    if (progressText) {
        if (message) {
            progressText.textContent = message;
        } else if (total === 100) {
            // 当使用百分比模式时，只显示百分比
            progressText.textContent = `${percentage.toFixed(0)}%`;
        } else {
            // 当使用计数模式时，显示 current/total (percentage%)
            progressText.textContent = `${current}/${total} (${percentage.toFixed(0)}%)`;
        }
    }
}

// 添加日志到页面 - 参考 batch-combine3 的实现
function addLog(message, isError = false) {
    if (!logContainer) return;
    
    const logItem = document.createElement('div');
    
    logItem.className = isError ? 'error-log' : 'info-log';
    logItem.style.color = isError ? '#ff4d4f' : '#52c41a';
    logItem.style.marginBottom = '5px';
    
    const timestamp = new Date().toLocaleTimeString();
    logItem.textContent = `[${timestamp}] ${message}`;
    
    logContainer.appendChild(logItem);
}

// 处理环境切换
function handleAddressSwitch() {
    // 新的 HTML 结构使用 CSS 自动处理标签显示，无需手动更新
    console.log('环境切换:', envSwitch ? (envSwitch.checked ? 'PRD' : 'UAT') : 'UAT');
}

// 处理无头模式切换
function handleStepsSwitch() {
    // 新的 HTML 结构使用 CSS 自动处理标签显示，无需手动更新
    console.log('模式切换:', headlessSwitch ? (headlessSwitch.checked ? '显示步骤（有头模式）' : '隐藏步骤（无头模式）') : '隐藏步骤（无头模式）');
}

// UI 初始化
function initializeUI() {
    // 设置初始状态
    updateProcessingState(false);
    
    // 隐藏进度条
    progressManager.hide();
    
    // 隐藏日志容器
    if (logContainer) {
        logContainer.style.display = 'none';
    }
}

// 文件上传处理
async function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
        ElMessage.error('请选择 Excel 文件 (.xlsx 或 .xls)');
        return;
    }

    try {
        uploadedData = await parseExcelFile(file);
        
        if (uploadedData.length > 0) {
            ElMessage.success(`成功上传文件，共 ${uploadedData.length} 条数据`);
            updateDataPreview(uploadedData);
            if (startButton) startButton.disabled = false;
        } else {
            ElMessage.warning('文件中没有找到有效数据');
        }
    } catch (error) {
        console.error('文件解析失败:', error);
        ElMessage.error(`文件解析失败: ${error.message}`);
    }
}

// Excel 文件解析
async function parseExcelFile(file) {
    try {
        const fileBuffer = await file.arrayBuffer();
        
        console.log('开始解析 Excel 文件:', file.name);
        
        // 使用 XLSX 库直接解析文件
        const workbook = XLSX.read(fileBuffer, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const rawData = XLSX.utils.sheet_to_json(worksheet, { defval: '' });
        
        // 定义需要转换为小写的字段 - 与 main.ts 中的逻辑保持一致
        const lowercaseFields = [
            '是否单一分包实验室',
            'Assign Sample',
            'Quotation Save',
            'Quotation Generate',
            'Quotation Confirm',
            'Order Confirm',
        ];
        
        // 处理数据，对指定字段进行小写转换
        const processedData = rawData.map((row) => {
            const processedRow = {};
            for (const [key, value] of Object.entries(row)) {
                // 统一处理字符串类型值
                const strValue = typeof value === 'string' ? value.trim() : String(value).trim();
                
                // 对指定字段进行小写转换
                processedRow[key] = lowercaseFields.includes(key) 
                    ? strValue.toLowerCase()
                    : strValue;
            }
            return processedRow;
        });
        
        console.log('Excel 解析结果:', processedData);
        
        return processedData;
    } catch (error) {
        console.error('parseExcelFile 错误:', error);
        throw error;
    }
}

// 数据预览更新
function updateDataPreview(data) {
    if (!dataPreview || data.length === 0) return;

    const previewContent = document.getElementById('preview-content');
    if (!previewContent) return;

    // 创建表格包装器
    const tableWrapper = document.createElement('div');
    tableWrapper.className = 'table-wrapper';
    
    const table = document.createElement('table');
    table.className = 'data-table';

    // 表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    const headers = Object.keys(data[0]);
    
    headers.forEach(header => {
        const th = document.createElement('th');
        th.textContent = header;
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    table.appendChild(thead);

    // 表体
    const tbody = document.createElement('tbody');
    data.slice(0, 5).forEach(row => { // 只显示前5行
        const tr = document.createElement('tr');
        headers.forEach(header => {
            const td = document.createElement('td');
            td.textContent = row[header] || '';
            tr.appendChild(td);
        });
        tbody.appendChild(tr);
    });
    table.appendChild(tbody);

    tableWrapper.appendChild(table);
    
    previewContent.innerHTML = '';
    previewContent.appendChild(tableWrapper);
    dataPreview.style.display = 'block';

    if (data.length > 5) {
        const moreInfo = document.createElement('p');
        moreInfo.textContent = `... 还有 ${data.length - 5} 行数据`;
        moreInfo.style.textAlign = 'center';
        moreInfo.style.color = '#ccc';
        moreInfo.style.marginTop = '10px';
        previewContent.appendChild(moreInfo);
    }
}

// 下载模板
async function downloadTemplate() {
    try {
        console.log('开始下载模板');
        
        // 模板文件路径
        const templatePath = 'NewSubcontract template.xlsx';
        
        // 获取模板文件
        const response = await fetch(templatePath);
        if (!response.ok) {
            throw new Error(`无法获取模板文件: ${response.status} ${response.statusText}`);
        }
        
        // 获取文件内容
        const blob = await response.blob();
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'NewSubcontract template.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        // showCustomMessage('success', '模板下载成功');
        console.log('模板下载完成');
    } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error(`模板下载失败: ${error.message}`);
    }
}

// 开始处理
async function startProcessing() {
    if (isProcessing) return;
    
    if (uploadedData.length === 0) {
        ElMessage.warning('请先上传 Excel 文件');
        return;
    }

    isProcessing = true;
    updateProcessingState(true);
    
    // 显示进度条和日志
    progressManager.show();
    
    // 清空并显示日志容器
    const logContent = document.getElementById('log-content');
    if (logContent) {
        logContent.innerHTML = '';
    }
    if (logContainer) {
        logContainer.style.display = 'block';
    }
    
    // 清空结果容器
    if (resultContainer) {
        resultContainer.innerHTML = '';
        resultContainer.style.display = 'none';
    }
    
    const environment = envSwitch ? (envSwitch.checked ? 'PRD' : 'UAT') : 'UAT';
    const isHeadless = headlessSwitch ? headlessSwitch.checked : true; // 当开关打开时隐藏步骤（无头模式），关闭时显示步骤（有头模式）
    
    addLog(`开始处理 ${uploadedData.length} 个订单`);
    // addLog(`环境: ${environment}, 无头模式: ${isHeadless}`);
    
    // 显示处理中消息
    processingMessage = ElMessage.info('Processing...');
    
    try {
        // 获取用户设置
        let userSettings = {};
        try {
            userSettings = await window.electronAPI.getUserSettings();
        } catch (error) {
            console.warn('无法获取用户设置:', error);
        }
        
        // 脚本执行前更新进度
        updateProgress(0, uploadedData.length, true, `0/${uploadedData.length} (0%)`);
        
        const result = await processOrders(uploadedData, environment, isHeadless, userSettings);
        
        // 脚本执行完成后更新进度
        const processedCount = result.processedCount || uploadedData.length;
        updateProgress(processedCount, uploadedData.length, true, `${processedCount}/${uploadedData.length} (100%)`);
        
        // 关闭处理中消息
        if (processingMessage && processingMessage.close) {
            processingMessage.close();
            processingMessage = null;
        }
        
        if (result.success) {
            ElMessage.success('Finished!');
            
            // 显示处理结果
            if (result.details && Array.isArray(result.details)) {
                displayResults(result.details);
                const successCount = result.details.filter(item => item.success).length;
                const failCount = result.details.filter(item => !item.success).length;
                
                addLog(`处理完成，成功: ${successCount}，失败: ${failCount}`);
            } else if (result.data && Array.isArray(result.data)) {
                displayResults(result.data);
                const successCount = result.data.filter(item => item.success).length;
                const failCount = result.data.filter(item => !item.success).length;
                
                addLog(`处理完成，成功: ${successCount}，失败: ${failCount}`);
            } else if (result.data && result.data.details && Array.isArray(result.data.details)) {
                displayResults(result.data.details);
                const successCount = result.data.details.filter(item => item.success).length;
                const failCount = result.data.details.filter(item => !item.success).length;
                
                addLog(`处理完成，成功: ${successCount}，失败: ${failCount}`);
            } else if (result.processedCount !== undefined && result.totalCount !== undefined) {
                addLog(`处理完成，成功: ${result.processedCount}，总计: ${result.totalCount}`);
            } else {
                addLog('所有订单处理完成');
            }
            
            // 延迟后隐藏进度条
            setTimeout(() => updateProgress(0, uploadedData.length, false), 1000);
        } else {
            throw new Error(result.error || '处理失败');
        }
    } catch (error) {
        // 出错时重置进度条
        updateProgress(0, uploadedData.length, true, `0/${uploadedData.length} (0%)`);
        
        // 关闭处理中消息
        if (processingMessage && processingMessage.close) {
            processingMessage.close();
            processingMessage = null;
        }
        
        // 添加错误日志
        addLog(error.message || '处理失败', true);
        
        ElMessage.error('Failed, Please check.');
    } finally {
        // 重新启用按钮
        isProcessing = false;
        updateProcessingState(false);
    }
}

// 停止处理
async function stopProcessing() {
    if (!isProcessing) return;
    
    try {
        ElMessage.warning('正在停止处理...');
        addLog('用户请求停止处理');
        
        // 使用 batch-combine3 的实现方式
        const result = await pluginAPI.stopPluginScript();
        
        if (result.success) {
            addLog('处理已停止');
        }
    } catch (error) {
        console.error('停止处理失败:', error);
        addLog(`停止处理失败: ${error.message}`, true);
    }
    
    isProcessing = false;
    updateProcessingState(false);
}

// 处理订单
async function processOrders(data, environment, isHeadless, userSettings) {
    try {
        const result = await window.pluginAPI.runPluginScript({
            pluginName: 'new-subcontract2',
            script: 'core.js',
            args: [data, environment, isHeadless, userSettings || {}]
        });
        
        return result;
    } catch (error) {
        console.error('processOrders 错误:', error);
        throw error;
    }
}

// 更新处理状态
function updateProcessingState(processing) {
    if (startButton) startButton.disabled = processing || uploadedData.length === 0;
    if (stopButton) stopButton.disabled = !processing;
    if (fileInput) fileInput.disabled = processing;
    if (envSwitch) envSwitch.disabled = processing;
    if (headlessSwitch) headlessSwitch.disabled = processing;
}



// 检查插件 API
function checkPluginAPI() {
    if (!pluginAPI) {
        console.error('pluginAPI disabled');
        ElMessage.error('pluginAPI 不可用，请检查系统配置');
        return false;
    }
    
    const requiredMethods = ['runPluginScript', 'stopPluginScript'];
    const missingMethods = requiredMethods.filter(method => !pluginAPI[method]);
    
    if (missingMethods.length > 0) {
        console.error('缺少 pluginAPI 方法:', missingMethods);
        ElMessage.error(`pluginAPI 不完整，缺少方法: ${missingMethods.join(', ')}`);
        return false;
    }
    
    console.log('pluginAPI 检查通过');
    return true;
}

// 显示处理结果的函数 - 参考 batch-combine3 的完整实现
function displayResults(results) {
    if (!resultContainer) return;
    
    // 清空容器
    resultContainer.innerHTML = '';
    
    // 创建结果标题
    const resultTitle = document.createElement('h3');
    resultTitle.textContent = 'New Subcontract 操作结果';
    resultTitle.style.marginTop = '20px';
    resultTitle.style.color = '#fff';
    resultContainer.appendChild(resultTitle);
    
    // 显示处理统计信息
    const statsDiv = document.createElement('div');
    statsDiv.style.marginBottom = '15px';
    statsDiv.style.fontSize = '14px';
    statsDiv.style.color = '#fff';
    
    // 计算成功和失败的数量
    const totalCount = results.length;
    const successCount = results.filter(result => result.success).length;
    const failureCount = totalCount - successCount;
    
    statsDiv.innerHTML = `总共处理: <strong>${totalCount}</strong> 条订单, 成功: <strong class="status-success">${successCount}</strong>, 失败: <strong class="status-failed">${failureCount}</strong>`;
    resultContainer.appendChild(statsDiv);
    
    // 创建表格包装器以支持水平滚动
    const tableWrapper = document.createElement('div');
    tableWrapper.className = 'table-wrapper';
    
    // 创建结果表格
    const resultTable = document.createElement('table');
    resultTable.className = 'result-table';
    
    // 创建表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    ['订单号', '状态', '详情', '记录状态'].forEach(text => {
        const th = document.createElement('th');
        th.textContent = text;
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    resultTable.appendChild(thead);
    
    // 创建表格内容
    const tbody = document.createElement('tbody');
    results.forEach(result => {
        const row = document.createElement('tr');
        
        // 订单号
        const orderNoCell = document.createElement('td');
        orderNoCell.textContent = result.orderNo || result['Order No.'] || '-';
        row.appendChild(orderNoCell);
        
        // 状态
        const successCell = document.createElement('td');
        successCell.textContent = result.success ? '成功' : '失败';
        successCell.className = result.success ? 'status-success' : 'status-failed';
        row.appendChild(successCell);
        
        // 详情
        const messageCell = document.createElement('td');
        messageCell.textContent = result.message || result.error || '-';
        messageCell.className = 'detail-cell';
        row.appendChild(messageCell);
        
        // 监控记录状态 - 参考 batch-combine3 的实现
        const monitoringCell = document.createElement('td');
        
        // 添加调试日志
        console.log(`订单 ${result.orderNo || result['Order No.']} 的监控状态:`, {
            hasMonitoringStatus: result.hasOwnProperty('monitoringStatus'),
            monitoringStatus: result.monitoringStatus,
            monitoringStatusType: typeof result.monitoringStatus,
            monitoringStatusStringified: JSON.stringify(result.monitoringStatus),
            monitoringMessage: result.monitoringMessage
        });
        
        // 根据监控状态设置显示内容和样式
        if (result.success) {
            if (result.monitoringStatus === true) {
                monitoringCell.textContent = '记录成功';
                monitoringCell.className = 'status-success';
                monitoringCell.title = result.monitoringMessage || '监控数据发送成功';
            } else if (result.monitoringStatus === false) {
                monitoringCell.textContent = '记录失败';
                monitoringCell.className = 'status-processing';
                monitoringCell.title = result.monitoringMessage || '监控数据发送失败';
            } else {
                monitoringCell.textContent = '未记录';
                monitoringCell.className = 'status-processing';
                monitoringCell.title = '未尝试发送监控数据';
            }
        } else {
            monitoringCell.textContent = '不适用';
            monitoringCell.className = 'status-processing';
            monitoringCell.title = '操作未成功，不发送监控数据';
        }
        
        row.appendChild(monitoringCell);
        
        tbody.appendChild(row);
    });
    resultTable.appendChild(tbody);
    
    tableWrapper.appendChild(resultTable);
    resultContainer.appendChild(tableWrapper);
    
    // 显示结果容器
    resultContainer.style.display = 'block';
}

// 导出函数供外部使用
window.newSubcontract2 = {
    ElMessage,
    ProgressManager,
    LogManager,
    startProcessing,
    stopProcessing,
};